package com.liying;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class Converter {

	/**
	 * 从文件读取json数据
	 * 
	 * @param fileName
	 * @return
	 */
	public String readJsonFromFile(String fileName) {
		StringBuffer strBuf = new StringBuffer();
		try {
			FileInputStream fis = new FileInputStream(fileName);
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = fis.read(buf)) != -1) {
				strBuf.append(new String(buf, 0, len));
			}

		} catch (FileNotFoundException e) {
			// e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return strBuf.toString();
	}

	/**
	 * 从JSON数据构建图
	 * 
	 * @param jsonStr
	 */
	public Graph jsonToGraph(String jsonStr) {
		Graph graph = null;
		try {

			JSONTokener jsonParser = new JSONTokener(jsonStr);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();

			JSONArray nodeArray = jsonObj.getJSONArray("nodes");
			JSONArray edgeArray = jsonObj.getJSONArray("edges");

			graph = new Graph(nodeArray.length(), edgeArray.length());

			for (int i = 0; i < nodeArray.length(); i++) {
				JSONObject nodeObj = nodeArray.getJSONObject(i);
				graph.addNode(nodeObj.getInt("din"), nodeObj.getInt("dout"),
						nodeObj.getInt("dtotal"), nodeObj.getString("id"),
						nodeObj.getString("label"), nodeObj.getDouble("size"),
						nodeObj.getInt("state"), nodeObj.getDouble("x"),
						nodeObj.getDouble("y"));
			}
			for (int i = 0; i < edgeArray.length(); i++) {
				JSONObject obj = edgeArray.getJSONObject(i);
				graph.addEdge(obj.getString("id"), obj.getString("source"),
						obj.getInt("state"), obj.getString("target"),
						obj.getInt("value"));
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return graph;
	}

	/**
	 * 将图转化为JSON数据
	 * 
	 * @param graph
	 */
	public void graphToJson(Graph graph) {

	}

	/**
	 * 将预测边转化为JSON数据, 保存到文件
	 * 
	 * @param topList
	 */
	public JSONArray topResultToJsonArray(List<Edge> topList, int edgeNo) {
		JSONArray edgeArray = new JSONArray();
		try {
			for (Edge edge : topList) {
				JSONObject edgeObj = new JSONObject();
				edgeObj.put("id", "e" + Integer.toString(++edgeNo));
				edgeObj.put("source", edge.getSource());
				edgeObj.put("state", 0);
				edgeObj.put("target", edge.getTarget());
				edgeObj.put("value", edge.getValue());

				edgeArray.put(edgeObj);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return edgeArray;
	}

}
